<template>

	<a-modal
		v-model:visible="modalCtr.visible"
		:title="`${modalCtr.title}批量导入`"
		:width="modalCtr.width"
    :align-center="false"
    :top="50"
		:footer="modalCtr.footer"
		:mask-closable="modalCtr.maskClosable"
		:keyboard="modalCtr.keyboard"
		:closable="modalCtr.closable">


		<!--上传选择框-->
		<a-upload
			v-model:file-list="uploadCtr.fileList"
			name="file" draggable
      :max-count="uploadCtr.maxCount"
			:multiple="uploadCtr.multiple"
			:accept="uploadCtr.accept"
      :auto-upload="false"
			:before-upload="beforeUpload">
			<div class="upload-box">
				<p>
					<a-typography-text>
						<smart-icon name="ri-file-excel-line" :size="36" />
					</a-typography-text>
				</p>
				<p>
					<a-typography-text type="disabled">请选择或拖拽需要上传的Excle文件到此区域</a-typography-text>
				</p>
				<p>
					<a-typography-text type="secondary">仅支持xls或xlsx格式的的文件</a-typography-text>
				</p>
			</div>
		</a-upload>

		<div v-if="uploadResult.show" class="result">
			<p>
				<a-typography-text type="primary">本次导入表格总共:{{ uploadResult.allCount }}条数据,</a-typography-text>
				<a-typography-text type="success">其中成功 {{ uploadResult.successCount }}条数据,</a-typography-text>
				<a-typography-text type="danger">失败{{ uploadResult.failCount }}条数据</a-typography-text>

			</p>

			<p>
				<a-space>
					<a-button v-if="uploadResult.downUrl"  type="primary"  @click="uploadResult.downLoadResult">下载导入结果</a-button>
					<a-button status="warning" @click="uploadResult.nextUpload">继续导入</a-button>
					<a-button @click="onClose">关闭窗口</a-button>
				</a-space>
			</p>
		</div>

		<div v-else class="tplBox">
			<p class="mode">
				导入重复主键时:
				<a-radio-group v-model="formState.mode">
					<a-radio value="ONLY_INSERT">仅处理新增数据</a-radio>
					<a-radio value="ONLY_UPDATE">仅处理修改数据</a-radio>
					<a-radio value="AUTO">自动处理新增或更新</a-radio>
				</a-radio-group>
			</p>

			<p>
				<a-space>
					<a-button :disabled="!uploadCtr.fileList.length" :loading="uploadCtr.loading" type="primary" @click="sendRequest">
						{{ uploadCtr.loading ? '数据导入中...' : '执行导入' }}
					</a-button>
					<a-button @click="onClose">关闭窗口</a-button>
				</a-space>
			</p>
		</div>

		<div class="tips">
			<p style="text-align: center">
				<a-link @click="downLoadTpl"  >
					<smart-icon name="icon-download" :size="20" style="margin-right: 6px" />
					点击下载{{ modalCtr.title }}导入模板
				</a-link>
			</p>

      <p v-if="props.tips" style="color: red">{{tips}}</p>
			<p>在数据导入过程中，如果涉及到日期字段，请按以下示例: 2022-01-01填充</p>
			<p>建议单次导入数据不超过5000条，以免影响系统正常操作性能</p>
			<p>大批量数据导入请避免高峰期操作，以免影响正常操作</p>
		</div>
		<!--上传文件-->
	</a-modal>
</template>
<script lang="ts" setup name="smart-upload-xls">
import { reactive, ref } from 'vue'
import { Upload } from '@arco-design/web-vue'
import { EmptyUtil, ReUtil, RequestUtil, MsgUtil } from '@/utils'
 import {CloseModelEvent} from "@/types";

const props = defineProps({
	tplPath: {
		type: String,
		require: true,
	},
	title: {
		type: String,
		require: true,
	},
	uploadPath: {
		type: String,
		require: true,
	},
  tips: {
    type: String,
    require: false,
  },
})

const emit = defineEmits(['close'])

const modalCtr = reactive({
	visible: true,
	title: props.title,
	width: 700,
	footer: null,
	destroyOnClose: true,
	keyboard: false,
	closable: false,
	maskClosable: false,
})
const uploadCtr = reactive({
	fileList: [],
  maxCount:1 ,
	multiple: false,
	loading: false,
	accept: '.xls,.xlsx',
})

const uploadResult = reactive({
	show: false,
	allCount: 0,
	successCount: 0,
	failCount: 0,
	ignoreCount: 0,
	downUrl: null,
	downLoadResult:()=>window.open(uploadResult.downUrl),
	nextUpload: () => {
		uploadCtr.fileList = []
		uploadResult.show = false
		uploadResult.allCount = 0
		uploadResult.successCount = 0
		uploadResult.failCount = 0
		uploadResult.ignoreCount = 0
		uploadResult.downUrl = null
	},
})

// Excle 模板文件下载地址
const tplExclePath = ref(null)
const downLoadTpl = async () => {
	if (EmptyUtil.isEmptyString(tplExclePath.value)) {
		if (ReUtil.isExternalLink(tplExclePath.value)) {
			tplExclePath.value = props.tplPath
		} else {
			const { data } = await RequestUtil.getAjax(props.tplPath)
			tplExclePath.value = data
		}
	}
	window.open(tplExclePath.value)
}
const onClose = () => {
	modalCtr.visible = false
	// @ts-ignore
	const e: CloseModelEvent = uploadResult.successCount > 0 ? 'RELOAD' : 'NONE'
	emit('close', e)
}
const formState = reactive({
	mode: 'ONLY_INSERT',
})

const beforeUpload = file => {
	const isExcle = file.name.endsWith('.xls') || file.name.endsWith('.xlsx')
	if (!isExcle) {
		MsgUtil.message(`${file.name} 不是合法的Excle文件格式`, 'error')
		return Upload.LIST_IGNORE
	}

	if (file.size > 1024 * 1024 * 5) {
		MsgUtil.message(`上传的Excle文件不能5MB `, 'error')
		return Upload.LIST_IGNORE
	}

	uploadCtr.fileList = [...uploadCtr.fileList, file]
	return false
}
// 上传执行
const sendRequest = async () => {
	const file = uploadCtr.fileList[0].file
	uploadCtr.loading = true
	// 封装源数据
	const formData = new FormData()
	formData.append('file', file)
	formData.append('mode', formState.mode)
	// 构造进度监听方法
	const getProgress = progressEvent => {
		file.percent = (progressEvent.loaded / progressEvent.total) * 100
	}

	try {
		const {
			data: { allCount, successCount, failCount, downUrl },
		} = await RequestUtil.uploadAjax(props.uploadPath, formData, getProgress)
		uploadResult.show = true
		uploadResult.allCount = allCount
		uploadResult.failCount = failCount
		uploadResult.successCount = successCount
		uploadResult.downUrl = downUrl
	} catch (e) {
		uploadResult.show = false
	} finally {
		uploadCtr.fileList = []
		uploadCtr.loading = false
	}
}
</script>

<style scoped lang="less">
.upload-box {
	p {
		text-align: center;
		margin-top: 12px;
	}
}

.tplBox {
	p {
		text-align: center;
		margin-top: 12px;
	}
}

.result {
	p {
		text-align: center;
		margin-top: 12px;
	}
}

.tips {
  background-color: var(--color-bg-1);
	border-top: 1px solid var(--color-border);
	padding: 12px;
}
</style>
